package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy*
 * @package: com.elite.groovy.callback*
 * @className: apiIVRMissedCall*
 * @description: 用于接收天润推动来电挂断数据，给ivr放弃、队列中溢出、响铃未接听电话发送短信。
 * @author: tian*
 * @date: 2024-02-19 15:00
 * @version: 1.0
 */

class apiIVRMissedCall implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiIVRMissedCall.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String getMethod = request.getMethod();
        log.debug("apiClinkCallback getMethod:" + getMethod);
        String outData = "FAIL";

        //获取所有参数名
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String parameterName = (String) ep.nextElement();
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取调用数据
        String callBody = Util.getRequestBody(request, "UTF-8");
        log.info("接收调用 POST 参数信息：" + callBody);

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 解析调用推送方式
        JSONObject callJson = JSONObject.fromObject(callBody);
        String cdr_call_type = KHUtil.GetSFJV(callJson, "cdr_call_type");//呼叫类型
        String cdr_status = KHUtil.GetSFJV(callJson, "cdr_status"); //呼叫状态
        String cdr_queue = KHUtil.GetSFJV(callJson, "cdr_queue");//进入队列号
        String cdr_end_reason = KHUtil.GetSFJV(callJson, "cdr_end_reason");//挂机原因
        String cdr_customer_number = KHUtil.GetSFJV(callJson, "cdr_customer_number");//客户号码
        String bindTel = KHUtil.GetSFJV(callJson, "bindTel");//绑定电话（坐席工号）

        // 固定发送75l7b0模板
        String querySQL = "select doctemplate_id,description,documentpath,documentpath2 from doctemplate where doctemplate_id='WTS2DF' and status='1' Limit 1";
        //String querySQL = "select doctemplate_id,description,documentpath,documentpath2 from doctemplate where doctemplate_id='TVSLZ6' and status='1' Limit 1";
        List querySQLR=eliteBean.chaxun_sql(querySQL,"dataSource");
        String description ="";
        String documentpath ="";
        String documentpath2 ="";
        String doctemplate_id ="";
        if(querySQLR.size()>0){
            description = querySQLR.get(0).get("description");
            documentpath = querySQLR.get(0).get("documentpath");
            documentpath2 = querySQLR.get(0).get("documentpath2");
            doctemplate_id = querySQLR.get(0).get("doctemplate_id");
        }else{
            log.debug("未查询到短信模板:75l7b0");
        }

        //呼入+系统接听+队列号不为空+绑定电话（坐席工号）为空||坐席未接听
        if ((cdr_call_type == "1" && cdr_status == "3" && !KHUtil.isNull(cdr_queue) && KHUtil.isNull(bindTel)) || cdr_status == "2") {
            sendDataDB(eliteBean, '3', documentpath, documentpath2, "", "", "", "", "", cdr_customer_number, doctemplate_id, "");
        }
        return "SUCC";
    }

    // 添加document表，发送数据DB处理
    static int sendDataDB(EliteBean eliteBean, String Doctype, String Documentpath, String Documentpath2, String Comments, String Customer_Guid, String Objective_Guid, String documentfrom, String Stringfield1, String documentto, String Template_Id, String linkURL) {
        long startTime = System.currentTimeMillis()
        log.debug("开始将发送内容数据处理到DB:" + startTime)
        int executeRow = 0
        try {
            def InsertSQL = "Insert Into Documentout" +
                    "  (Documentout_Guid," +
                    "   Doctype," +
                    "   Status," +
                    "   Trialcount," +
                    "   Trialcountlimit," +
                    "   Documentpath," +
                    "   Comments," +
                    "   Documentto," +
                    "   Priority_Id," +
                    "   Customer_Guid," +
                    "   Objective_Guid," +
                    "   Createdby," +
                    "   Createddate," +
                    "   documentfrom," +
                    "   Stringfield1," +
                    "   Documentpath2," +
                    "   Template_Id," +
                    "   Expectedstartdate," +
                    "   send_url)" +
                    "Values" +
                    "  (Uuid()," +
                    "   '" + Doctype + "'," +
                    "   0," +
                    "   0," +
                    "   3," +
                    "   '" + Documentpath + "'," +
                    "   '" + Comments + "'," +
                    "   '" + documentto + "'," +
                    "   '1'," +
                    "   '" + Customer_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   '" + documentfrom + "'," +
                    "   '" + Stringfield1 + "'," +
                    "   '" + Documentpath2 + "'," +
                    "   '" + Template_Id + "'," +
                    "   Now()," +
                    "   '" + linkURL + "')"
            executeRow = eliteBean.update(InsertSQL, "dataSource")

            long endTime = System.currentTimeMillis()
            log.debug("发送内容数据处理到DB时长(毫秒):" + (endTime - startTime))

        } catch (Exception e) {
            long endTime = System.currentTimeMillis()
            log.error("发送内容数据处理到DB时长(毫秒):" + (endTime - startTime) + " 处理失败(" + e.getMessage() + ")")
        }

        return executeRow
    }
}